package com.itheima.interceptor;

import com.alibaba.fastjson2.JSON;
import com.itheima.utils.Result;
import io.jsonwebtoken.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/10 16:47
 * @Desc:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头里token携带的jwt令牌信息
        String jwt = request.getHeader("token");
        //判断令牌是否存在，不存在则向浏览器响应未登录的响应信息
        if (!StringUtils.hasLength(jwt)) {
            response.getWriter().write(JSON.toJSONString(Result.error("NOT_LOGIN")));
            return false;
        }

        //解析令牌
        try {
            Jwts.parser()
                    .setSigningKey("itheima")
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            //触发异常，说明令牌无效，向浏览器响应未登录的响应信息
            response.getWriter().write(JSON.toJSONString(Result.error("NOT_LOGIN")));
            return false;
        }

        //令牌信息正确，放行请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
